package com.asset.service.impl;

import com.asset.mapper.CompanyMapper;
import com.asset.model.entity.Company;
import com.asset.service.CompanyService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.util.CollectionUtils;

import java.util.List;
import java.util.stream.Collectors;

@Service
public class CompanyServiceImpl  implements CompanyService {

    @Autowired
    private CompanyMapper companyMapper;
    // 构建组织架构树（递归方式）
    public List<Company> buildCompanyTree() {
        List<Company> allCompanies = companyMapper.selectAll();
        // 查找根节点（parent_id 为 null，即集团）
        List<Company> rootNodes = allCompanies.stream()
                .filter(company -> company.getParentId() == null)
                .collect(Collectors.toList());
        // 递归构建子节点
        for (Company root : rootNodes) {
            buildChildren(root, allCompanies);
        }
        return rootNodes;
    }

    // 递归构建子节点
    public void buildChildren(Company parent, List<Company> allCompanies) {
        List<Company> children = allCompanies.stream()
                .filter(company -> parent.getId().equals(company.getParentId()))
                .collect(Collectors.toList());
        if (!CollectionUtils.isEmpty(children)) {
            parent.setChildren(children);
            for (Company child : children) {
                buildChildren(child, allCompanies);
            }
        }
    }
}
